﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NetMicro.Cache;

namespace NetMicro.EventBus.Trackers
{
    public class RedisTracker : IConsumerTracker
    {

        private readonly IRedisCache _redis;
        private readonly IOptions<EventBusOptions> _options;
        private readonly ILogger<RedisTracker> _logger;

        public RedisTracker(IRedisCache redis, IOptions<EventBusOptions> options, ILogger<RedisTracker> logger)
        {
            _redis = redis;
            _options = options;
            _logger = logger;
        }


        public bool HasProcessed(string eventId)
        {
            try
            {
                return _redis.Exists($"{EventBusConsts.TrackerKey}:{eventId}");
            }
            catch (Exception ex)
            {
                _logger.LogWarning($"幂等判断出现异常：{ex}，幂等无效，不影响程序运行，及时解决");
                return true;
            }
        }

        public Task<bool> HasProcessedAsync(string eventId)
        {
            try
            {
                return _redis.ExistsAsync($"{EventBusConsts.TrackerKey}:{eventId}");
            }
            catch (Exception ex)
            {
                _logger.LogWarning($"幂等判断出现异常：{ex}，幂等无效，不影响程序运行，及时解决");
                return Task.FromResult(true);
            }
        }

        public bool MarkAsProcessed(string eventId)
        {
            try
            {
              
                return _redis.Set($"{EventBusConsts.TrackerKey}:{eventId}", eventId, _options.Value.TrackerExpired);
            }
            catch (Exception ex)
            {
                _logger.LogWarning($"幂等判断出现异常：{ex}，幂等无效，不影响程序运行，及时解决");
                return true;
            }
        }

        public Task<bool> MarkAsProcessedAsync(string eventId)
        {
            try
            {
                return _redis.SetAsync($"{EventBusConsts.TrackerKey}:{eventId}", eventId, _options.Value.TrackerExpired);
            }
            catch (Exception ex)
            {
                _logger.LogWarning($"幂等判断出现异常：{ex}，幂等无效，不影响程序运行，及时解决");
                return Task.FromResult(true);
            }
        }

    }
}
